package com.example.interesting.distributed.log.realize;

import cn.hutool.core.util.StrUtil;
import com.example.interesting.distributed.log.realize.constant.LogConstants;
import com.example.interesting.distributed.log.realize.util.LogTraceInit;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 基础的过滤器,不包括RPC调用
 * @Author: fyw
 * @Date: 2024/3/30 14:31
 * @History
 */
@Slf4j
public class BasicServletFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //定义自定义请求头的集合
            Map<String, String> headers = new HashMap<>();
            LogConstants.HEADER_KEYS.forEach(key -> {
                String header = request.getHeader(key);
                if (StrUtil.isNotBlank(header)) {
                    headers.put(key, header);
                }
            });
            //首次进入需要初始化
            LogTraceInit.fillTraceId(headers);
            log.info("请求链接日志信息：traceId={}，parentName={}", headers.get(LogConstants.LOG_TRACE_ID), headers.get(LogConstants.PARENT_SERVICE_NAME));
        } else {
            log.info("请求链接日志信息：非标准http请求不做日志链路");
        }
        //方法逻辑处理
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            //避免线程复用导致的上下文错误，释放资源
            MDC.clear();
        }
    }
}
